﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using Entity;
using System.Reflection;

/// <summary>
/// Summary description for TypedList
/// </summary>
public class TypedList<T> : List<T>
{
    DataTable dataTable;
    public TypedList(DataTable dataTable)
	{
        this.dataTable = dataTable;
        ConvertToEntity();
	}

    public void ConvertToEntity()
    {
        Type type = typeof(T);
        object instance = null;
        DataRowCollection rowCollection = dataTable.Rows;
        foreach (DataRow row in rowCollection)
        {
            instance = Activator.CreateInstance(type);
            PropertyInfo[] properties = instance.GetType().GetProperties();
            foreach (PropertyInfo property in properties)
            {
                Type propType = property.PropertyType;
                try
                {
                    if (propType.Name == "String")
                    {
                        property.SetValue(instance, row[property.Name].ToString(), null);
                    }
                    else if (propType.Name == "DateTime")
                    {
                        DateTime date = DateTime.Parse(row[property.Name].ToString());
                        property.SetValue(instance, date, null);
                    }
                    else
                    {
                        MethodInfo mi = propType.GetMethod("Parse");
                        property.SetValue(instance, mi.Invoke(null, new object[] { row[property.Name].ToString() }), null);
                    }
                }
                catch (Exception)
                {
                    property.SetValue(instance, null, null);
                }

            }
            Add((T)instance);
        } 
    }
}